#!/usr/bin/env node

/**
 * 测试1267指令的逻辑实现
 * 模拟BasicItemService和验证返回格式
 */

class MockBasicItemService {
    constructor() {
        // 模拟数据库中的物品数据
        this.items = {
            1: {
                id: 1,
                name: "跌打药",
                silverPrice: 50,
                lv: 1,
                weight: 1,
                description: "散瘀消肿，强筋健骨，可迅速补充气血。",
                pic: "dida.png",
                status: 1
            },
            2: {
                id: 2,
                name: "金创药",
                silverPrice: 100,
                lv: 2,
                weight: 1,
                description: "治疗外伤的良药，可快速恢复生命值。",
                pic: "jinchuang.png",
                status: 1
            },
            71: {
                id: 71,
                name: "铁矿石",
                silverPrice: 20,
                lv: 1,
                weight: 5,
                description: "常见的铁矿石，可用于锻造装备。",
                pic: "tiekuang.png",
                status: 1
            }
        };
    }

    async getItemById(id) {
        return this.items[id] || null;
    }
}

class ItemQueryHandler {
    constructor() {
        this.basicItemService = new MockBasicItemService();
    }

    async handleItemQuery(payload) {
        try {
            const { id } = payload;

            // 验证参数
            if (!id || typeof id !== "number") {
                return {
                    act_id: 1267,
                    code: -1,
                    msg: "物品ID不能为空且必须为数字",
                    data: [],
                };
            }

            // 查询物品信息
            const item = await this.basicItemService.getItemById(id);

            if (!item) {
                return {
                    act_id: 1267,
                    code: -1,
                    msg: "物品不存在",
                    data: [],
                };
            }

            // 构建返回数据格式
            const data = [
                { k: "名称:", v: item.name },
                { k: "价格:", v: `${item.silverPrice}两` },
                { k: "等级:", v: item.lv.toString() },
                { k: "负重:", v: item.weight.toString() },
                { k: "介绍:", v: item.description },
            ];

            return {
                act_id: 1267,
                code: 0,
                data: data,
            };
        } catch (error) {
            console.error("处理物品基础表查询指令1267失败:", error);
            return {
                act_id: 1267,
                code: -1,
                msg: "查询失败",
                data: [],
            };
        }
    }
}

class ItemQueryTester {
    constructor() {
        this.handler = new ItemQueryHandler();
        this.testResults = [];
    }

    addTestResult(testName, success, message, expected, actual) {
        this.testResults.push({
            test: testName,
            success: success,
            message: message,
            expected: expected,
            actual: actual
        });
    }

    async testValidItemQuery() {
        console.log('\n🧪 测试1: 有效物品查询');

        const payload = { id: 1 };
        const result = await this.handler.handleItemQuery(payload);

        console.log('📤 请求:', JSON.stringify(payload, null, 2));
        console.log('📨 响应:', JSON.stringify(result, null, 2));

        // 验证响应格式
        const isValid = result.act_id === 1267 &&
            result.code === 0 &&
            Array.isArray(result.data) &&
            result.data.length === 5 &&
            result.data[0].k === "名称:" &&
            result.data[0].v === "跌打药";

        this.addTestResult(
            '有效物品查询',
            isValid,
            isValid ? '查询成功' : '查询失败',
            'act_id: 1267, code: 0, data包含5个字段',
            `act_id: ${result.act_id}, code: ${result.code}, data长度: ${result.data.length}`
        );
    }

    async testNonExistentItem() {
        console.log('\n🧪 测试2: 不存在的物品查询');

        const payload = { id: 99999 };
        const result = await this.handler.handleItemQuery(payload);

        console.log('📤 请求:', JSON.stringify(payload, null, 2));
        console.log('📨 响应:', JSON.stringify(result, null, 2));

        // 验证错误响应
        const isValid = result.act_id === 1267 &&
            result.code === -1 &&
            result.msg === "物品不存在" &&
            Array.isArray(result.data) &&
            result.data.length === 0;

        this.addTestResult(
            '不存在物品查询',
            isValid,
            isValid ? '正确处理' : '处理错误',
            'act_id: 1267, code: -1, msg: "物品不存在"',
            `act_id: ${result.act_id}, code: ${result.code}, msg: "${result.msg}"`
        );
    }

    async testInvalidIdType() {
        console.log('\n🧪 测试3: 无效ID类型');

        const payload = { id: "invalid" };
        const result = await this.handler.handleItemQuery(payload);

        console.log('📤 请求:', JSON.stringify(payload, null, 2));
        console.log('📨 响应:', JSON.stringify(result, null, 2));

        // 验证错误响应
        const isValid = result.act_id === 1267 &&
            result.code === -1 &&
            result.msg === "物品ID不能为空且必须为数字" &&
            Array.isArray(result.data) &&
            result.data.length === 0;

        this.addTestResult(
            '无效ID类型',
            isValid,
            isValid ? '正确处理' : '处理错误',
            'act_id: 1267, code: -1, msg: "物品ID不能为空且必须为数字"',
            `act_id: ${result.act_id}, code: ${result.code}, msg: "${result.msg}"`
        );
    }

    async testMissingId() {
        console.log('\n🧪 测试4: 缺少ID参数');

        const payload = {};
        const result = await this.handler.handleItemQuery(payload);

        console.log('📤 请求:', JSON.stringify(payload, null, 2));
        console.log('📨 响应:', JSON.stringify(result, null, 2));

        // 验证错误响应
        const isValid = result.act_id === 1267 &&
            result.code === -1 &&
            result.msg === "物品ID不能为空且必须为数字" &&
            Array.isArray(result.data) &&
            result.data.length === 0;

        this.addTestResult(
            '缺少ID参数',
            isValid,
            isValid ? '正确处理' : '处理错误',
            'act_id: 1267, code: -1, msg: "物品ID不能为空且必须为数字"',
            `act_id: ${result.act_id}, code: ${result.code}, msg: "${result.msg}"`
        );
    }

    async testAnotherValidItem() {
        console.log('\n🧪 测试5: 另一个有效物品查询');

        const payload = { id: 71 };
        const result = await this.handler.handleItemQuery(payload);

        console.log('📤 请求:', JSON.stringify(payload, null, 2));
        console.log('📨 响应:', JSON.stringify(result, null, 2));

        // 验证响应格式
        const isValid = result.act_id === 1267 &&
            result.code === 0 &&
            Array.isArray(result.data) &&
            result.data.length === 5 &&
            result.data[0].k === "名称:" &&
            result.data[0].v === "铁矿石" &&
            result.data[1].v === "20两";

        this.addTestResult(
            '另一个有效物品查询',
            isValid,
            isValid ? '查询成功' : '查询失败',
            'act_id: 1267, code: 0, data包含铁矿石信息',
            `act_id: ${result.act_id}, code: ${result.code}, 物品名称: ${result.data[0]?.v}`
        );
    }

    printTestResults() {
        console.log('\n📊 测试结果汇总:');
        console.log('='.repeat(80));

        let successCount = 0;
        let totalCount = this.testResults.length;

        this.testResults.forEach((result, index) => {
            const status = result.success ? '✅' : '❌';
            console.log(`${index + 1}. ${status} ${result.test}: ${result.message}`);
            if (!result.success) {
                console.log(`   期望: ${result.expected}`);
                console.log(`   实际: ${result.actual}`);
            }
            if (result.success) successCount++;
        });

        console.log('='.repeat(80));
        console.log(`总计: ${successCount}/${totalCount} 测试通过`);

        if (successCount === totalCount) {
            console.log('🎉 所有测试通过！1267指令实现正确！');
        } else {
            console.log('⚠️ 部分测试失败，请检查实现。');
        }
    }

    async runAllTests() {
        console.log('🚀 开始测试1267指令 - 物品基础表查询功能');
        console.log('='.repeat(60));

        await this.testValidItemQuery();
        await this.testNonExistentItem();
        await this.testInvalidIdType();
        await this.testMissingId();
        await this.testAnotherValidItem();

        this.printTestResults();
    }
}

// 运行测试
if (require.main === module) {
    const tester = new ItemQueryTester();
    tester.runAllTests().catch(console.error);
}

module.exports = ItemQueryTester;
